//
//  YLNetworkTools.swift
//  afn
//
//  Created by 杨雷 on 2016/12/3.
//  Copyright © 2016年 Yang.L. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType {
    case get
    case post
}



class YLNetworkTools: AFHTTPSessionManager {
    
    
    
    
    typealias CallBack = (Any?, Error?) -> ()
    
    //单例 网络请求工具
    static let sharedTools: YLNetworkTools = {
        let tools = YLNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //封装get post
    
    func request (type: RequestType, url: String, parameters: Any?, callBack:@escaping CallBack) {
        
        if type == .get {
            get(url, parameters: parameters, progress: nil, success: { (_, response) in
                callBack(response, nil)
                
            }, failure: { (_, error) in
                callBack(nil, error)
            })
        } else {
            post(url, parameters: parameters, progress: nil, success: { (_, response) in
                
                callBack(response, nil)
            }, failure: { (_, error) in
                callBack(nil, error)
                
            })

        }
        
    }
    
}

//oAuth 相关
extension YLNetworkTools {
    
    //获取用户信息
    func requestUserInfo (accessToken: String, uid: Int64,callBack: @escaping CallBack) {
        let url = "https://api.weibo.com/2/users/show.json"
        let parameters = [
            "access_token": accessToken,
            "uid" : uid
        ] as [String : Any]
        request(type: .get, url: url, parameters: parameters, callBack: callBack)
        
    }
    
    
    //请求assesstoken
    func requestAccesstoken (code: String, callBack: @escaping CallBack) {
        //请求地址
        let url = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        let parameters = [
            "client_id" : AppKey,
            "client_secret" : AppSecret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : Redirect_uri
        ]
        
        //执行
        request(type: .post, url: url, parameters: parameters, callBack: callBack)
        
        
    }
    
    
}

//首页接口
extension YLNetworkTools {
    
    func requestStatus(callBack: @escaping CallBack) {
        //请求接口
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        //请求参数
        let params = [
            
            "access_token" : YLUserAccountViewModel.sharedUserAccount.accessToken!
            
        ]
        
        let path = url + "?access_token=" + YLUserAccountViewModel.sharedUserAccount.accessToken!
        
        //执行请求
        request(type: .get, url: url, parameters: params, callBack: callBack)
        
        
    }
    
    
}


















